//
//  SXPPublicViewController.swift
//  weibo
//
//  Created by shixinPeng on 16/3/6.
//  Copyright © 2016年 shixinPeng. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
let kHoldString = "宝宝心里苦,宝宝有苦说不出"

class SXPPublicViewController: UIViewController, UITextViewDelegate ,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
       var isAnimo: Bool = true
    var bottonConstraint:Constraint?

    override func viewDidLoad() {
        super.viewDidLoad()
        //view.backgroundColor = UIColor.whiteColor()
        
        setUpNav()
        
        setTextView()
        
        setToolView()
        
        //添加键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "tooBaiFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //添加添加表情的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "addEmotiocnToTextView:", name: SXPaddemoticonNotification, object: nil)
        //添加删除表情的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deteTextViewEmtion", name: SXPdeleteEmoticonClick, object: nil)
        
        
        
    }
    //添加工具栏
    private func setToolView() {
        //修改颜色
       toolbar.backgroundColor = UIColor.lightGrayColor()
        
        //添加按钮 利用数组 字典数组
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        //定义一个数组,来接收item 然后遍历数据数组,设置按钮的属性
        var items = [UIBarButtonItem]()
        
        for setting in itemSettings{
            //自定义button
            let barButton = UIButton(type: .Custom)
            
            //设置图片
            barButton.setImage(UIImage(named: setting["imageName"]!), forState: .Normal)
            
            //高亮图片
            let imageStr = setting["imageName"]!
            barButton.setImage(UIImage(named: "\(imageStr)_highlighted"), forState: .Highlighted)
            
            //设置大小
            barButton.sizeToFit()
            
            //添加点击方法
            if let actionStr = setting["action"] {
                barButton.addTarget(self, action: Selector(actionStr), forControlEvents: .TouchUpInside)
            }
            //赋值给barbuttonoitem
            let item = UIBarButtonItem(customView: barButton)
            
            //添加到数组中
            items.append(item)
            //每个barbutton后面加一个弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //移除最后一个多余的弹簧
        items.removeLast()
        //添加到toolbar中
        toolbar.items = items
        
        //添加视图中
        view.addSubview(toolbar)
        //设置约束
        toolbar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
            
            self.bottonConstraint = make.bottom.equalTo(view.snp_bottom).constraint
        }
    
    }
    
    //添加文本视图
    private func setTextView() {
        
        view.addSubview(textView)
        
        textView.frame = view.frame
        
        textView.holdString = kHoldString
        
        textView.font = UIFont.systemFontOfSize(16)

        
        textView.delegate = self
        
       
        
        //滑动界面让键盘自动消失
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .OnDrag
        
        //添加显示图片控件
        textView.addSubview(photoView)
        //设置约束
        photoView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(textView.snp_center)
            make.size.equalTo(CGSizeMake(kUISCREEN_W - (2 * photoviewMargin), kUISCREEN_W - (2 * photoviewMargin)))
        }
  
    }
    //MARK:--懒加载
    //文本视图的懒加载
    private lazy var textView:SXPtextView = SXPtextView()
    //工具栏的懒加载
    private lazy var toolbar:UIToolbar = UIToolbar()
    //中间图片区域
    private lazy var photoView:SXPphotoCollectionView = {
       
        let photoView = SXPphotoCollectionView()
        
        photoView.imageClosure = {[weak self]() -> () in
            
            self?.choosePicture()
            
        }
            
        
        return photoView
    }()
    //懒加载表情栏,设置frame
    private lazy var EmoticonView:SXPEmoticonView = {
        let emo = SXPEmoticonView()
        
        emo.frame.size = CGSizeMake(kUISCREEN_W,217)
    
        
        return emo
    }()
    
    deinit{
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardDidChangeFrameNotification, object: nil)
        
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name: SXPaddemoticonNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().removeObserver(self, name:SXPdeleteEmoticonClick , object: nil)
        printLog("发送界面88")
    }
    
    
    
//MARK: --导航栏方法
    private func setUpNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "push")
        navigationItem.rightBarButtonItem?.enabled = false
        
        //添加中间标题,自己定义一个label,然后修改其属性
        let titlelabel = UILabel(frame: CGRectMake(0,0,200,44))
        
        titlelabel.textAlignment = .Center
        
        let str = "发送微博 \n\(SXPuserViewModels.shareInstance.userModel?.screen_name ?? "")"
        
        //分为两行
        titlelabel.numberOfLines = 0
        //分别设置上下两部分的属性
        let attribute = NSMutableAttributedString(string: str)
        //上段属性
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(15)], range: NSMakeRange(0, 4))
        //下段属性
        attribute.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(13),NSForegroundColorAttributeName: UIColor.orangeColor()], range: NSMakeRange(4,str.characters.count - 4))
        
        titlelabel.attributedText = attribute
        
        //添加到导航栏
        navigationItem.titleView = titlelabel
    }


    @objc private func dismiss() {//返回
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    @objc private func push() {
        printLog("发布")
        SXPPublishViewModel().pushPublishWeibo(photoView.iamges,info: self.textView.attributedText) { () -> () in
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                
                
            })
        }
    }
    
    @objc private func tooBaiFrameChange(noti:NSNotification) {
 
        
//        if isAnimo {
//            return
//        }
        
        
        if let info = noti.userInfo {//获取信息
            //printLog(info)
            //let endFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
            
            let moveRect = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue
            
//            if endFrame?.origin.y == kUISCREEN_H {//提起
//                
//                
//            }else{//下落
//                `
//                
//            }
            
            /*
            分析弹出情况
            第一只考虑键盘的弹出和收回  这是默认的情况 动画刷新约束
            
            第二种情况,直接弹出收回表情界面 这种效果需要和第一种一样  +动画刷新约束
            
            第三种 表情界面和键盘界面的切换  不需要动画 ,直接到位
            
            
            
            
            
            */
            //利用三目运算解决约束移动
            //移除约束
            self.bottonConstraint?.uninstall()
            toolbar.snp_updateConstraints(closure: { (make) -> Void in
                
                self.bottonConstraint = make.bottom.equalTo(view.snp_bottom).offset(moveRect?.origin.y == kUISCREEN_H ? 0 : -moveRect!.height).constraint
            })
//            UIView.animateWithDuration(0.25, animations: { () -> Void in
//                                    self.toolbar.layoutIfNeeded()
//                
//                                })
            
            
            if  isAnimo {//切换或者弹出键盘 && 点击->图标成为成为响应者
                
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.toolbar.layoutIfNeeded()
                    
                })
            }
//            else if textView.inputView != nil  {//表情界面显示
//
//                UIView.animateWithDuration(0.25, animations: { () -> Void in
//                    self.toolbar.layoutIfNeeded()
//                    
//                })
//
//            }
     
            
        }
    }
    
    
    
}

// MARK: --toolBar中的方法
extension SXPPublicViewController{
    
    func choosePicture() {
        
        if photoView.iamges.count >= 9{
            
            SVProgressHUD.showErrorWithStatus("图片已达上限")
            return
        }
    
        
        /*
        case PhotoLibrary -- 相册
        case Camera         -- 相机
        case SavedPhotosAlbum -- 保存的相册
        */
        //访问手机相册,要先判断是否可以访问相册
        if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            //如果可以的话进行页面跳转
            let pick = UIImagePickerController()
            
            //设置类型,如果要使用相机,选择切换
            pick.sourceType = .PhotoLibrary
            
            //设置代理方法
            pick.delegate = self
            
            presentViewController(pick, animated: true, completion: { () -> Void in
                
            })
        }
        
        
    }
    //MARK: --插入表情按钮
 
    func inputEmoticon() {
        //不管有没有弹出文本输入框,都注销第一响应者,然后把表情框添加到弹出界面中 然后弹出表情框
        //插入按钮界面 先注销第一响应者,替换弹出界面
        
        isAnimo = false
        textView.resignFirstResponder()
        //printLog("输入键盘")
        
        
        /*
        
        inputview == nil 的时候表示没有弹出界面
        
        textView = nil 的时候弹出的就是键盘
        textView.input = emoticonView 的时候就是弹出自定义的视图
        下面的判段的作用是显示消失界面, 不是对文本键盘的操作
        */
        if textView.inputView == nil{
            
             isAnimo = false
            textView.inputView = EmoticonView
        }else{//此时有键盘的存在
            isAnimo = true
            textView.inputView = nil
            
        }
        
       
        textView.becomeFirstResponder()

    }
    
}
// MARK: --UIIMagePickerViewDelegate, UINavgationDealagte
extension SXPPublicViewController{
    //选取图片
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //传递照片
        photoView.addImage(image)
        
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    //取消按钮
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        printLog("取消imagePicker")
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    
}

// MARK: --uitextView的代理方法
extension SXPPublicViewController {
    
    func textViewDidChange(textView: UITextView) {
        
        if self.textView.hasText() {
  
            //有文字输入
            self.textView.holdString = ""
        }else{
            
            self.textView.holdString = kHoldString

        }
        //重绘
        self.textView.setNeedsDisplay()
        
        navigationItem.rightBarButtonItem?.enabled = self.textView.hasText()
    }
}
//MARK: --插入表情的通知响应方法
extension SXPPublicViewController {
    
    @objc private func deteTextViewEmtion(){
        
        textView.deleteBackward()
    }
    
    @objc private func addEmotiocnToTextView(noti: NSNotification) {
        //获取数据
        let emtion = noti.userInfo!["emotiion"] as! SXPEmoticonModel
        
        //printLog(emtion.chs)
        //把表情显示到textView上面
        if let Opng = emtion.png {
            //利用富文本 NSMutableAttributedString
            //1.把文本框里面副文本的值转变为可变的富文本,然后在把图片插入进去
            let preAttributedString = NSMutableAttributedString(attributedString: textView.attributedText)
            
            
            
            //2.准备图片
            let imagePath = emtion.imagPath!
            let img = UIImage(named: "\(imagePath)/\(Opng)")
            //printLog("\(imagePath)/\(Opng)")
            //3.把图片变为一个附件就可以
            let attachment = SXPtextAttachment()
            
            
            //设置文字大小
            //textView.font = UIFont.systemFontOfSize(16)
            //设置图片大小
            attachment.bounds = CGRectMake(0, -4, textView.font!.lineHeight, textView.font!.lineHeight)
            
            attachment.enotion = emtion
            
            attachment.image = img
            //把这个附件变为一个富文本
            let attributedString = NSAttributedString(attachment: attachment)
            
            //添加到当前的富文本中-->拼接方法
            //preAttributedString.appendAttributedString(attributedString)
            
            
            //解决不能插入头像的问题,先获取光标所在的位置
            let rang:NSRange = textView.selectedRange
            
            //插入到光标所在位置
            preAttributedString.insertAttributedString(attributedString, atIndex: rang.location)
            
            
            preAttributedString.addAttributes([NSFontAttributeName: textView.font!], range: NSMakeRange(0, preAttributedString.length))
            
            
            //最后 赋值到textView中
            textView.attributedText = preAttributedString
            
            
            
            //改变插入后光标的位置 光标向后移动一位
            textView.selectedRange = NSMakeRange(rang.location + 1 , 0)
        }
        //如果是emoji表情
        if let Oemoji = emtion.emoji {
            
            //获取文本
            let preAttributedString = NSMutableAttributedString(attributedString: textView.attributedText)
            
            //获取光标位置
            let rang = textView.selectedRange
            
            
            //插入
            preAttributedString.replaceCharactersInRange(NSMakeRange(rang.location, 0), withString:Oemoji)
          
           // preAttributedString.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16)], range: (NSMakeRange(rang.location, 0))
        
            preAttributedString.addAttributes([NSFontAttributeName: textView.font!], range: NSMakeRange(0, preAttributedString.length))
            
            textView.attributedText = preAttributedString
        }
        
        
        //判断文本框是否有值
        textView.delegate!.textViewDidChange!(textView)
        
        
    }
    
    
}

























